<template>
	<div class="centered-container">
		<div class="main-content">

			<div class="card">
				<h2>{{ characterName }}</h2>
				<!-- 图片或视频部分 -->
				<VideoPlayer v-if="!isVideoMessage" :videoUrl="videoUrl" :backUrl="backUrl" :pictureSrc="pictureSrc" />
				<VideoMessage v-if="isVideoMessage" :videoUrl="videoUrl" />

			</div>

			<!-- 聊天记录部分 -->
			<div class="chat-history" ref="chatHistory">
				<div v-if="chats && chats.length > 0">
					<div v-for="record in chats" :key="record.id">
						<ChatBubble :record="record" />
					</div>
				</div>
				<div v-show="chats && chats.length > 0" class="footer">
					<button @click="clearChatHistory" class="clear-button">清空聊天记录</button>
				</div>
			</div>

			<!-- 确认弹窗 -->
			<div v-if="showDialog" class="confirm-box">
				<div class="confirm-content">
					<p>是否确认清除全部聊天记录?</p>
					<button @click="confirm">确认</button>
					<button @click="cancel">取消</button>
				</div>
			</div>

			<!-- 对话文本框输入部分 -->
			<div class="chat-input-container">
				<textarea v-model="newMessage" placeholder="请输入消息..." class="chat-input-textarea"
					@keydown.enter.prevent="sendMessage"></textarea>
				<button @click="sendMessage" class="send-button">发送</button>
			</div>

			<!-- 导航栏 -->
			<NavBar :bPublic="bPublic" />
		</div>
	</div>

</template>

<script>
	import axios from 'axios';
	import ChatBubble from "@/components/ChatBubble.vue";
	import {
		startHeartbeat
	} from '@/websocket/heartbeat.js';
	import NavBar from '../components/NavBar.vue';
	import VideoPlayer from '@/components/VideoPlayer.vue';
	import VideoMessage from '../components/VideoMessage.vue';
	import {
		getPic
	} from '@/api/url_query'
	import '@/utils/sdk.js';
	import {
		trackWebfunnyEvent
	} from '@/utils/pointID.js'



	export default {
		components: {
			ChatBubble,
			NavBar,
			VideoPlayer,
			VideoMessage
		},

		data() {
			return {
				uid: '',
				characterName: '',
				cid: '',
				chats: [],
				newMessage: '',
				heartbeatStopper: null,
				isConnected: false,
				showDialog: false,
				videoUrl: '',
				backUrl: '',
				pictureSrc: '',
				canReplay: false, // 默认禁用按钮
				currentVideo: 1, // 用于跟踪当前播放的视频
				isVideoMessage: false,
				bPublic: false
			};
		},
		mounted() {
			// 获取传入的参数
			this.uid = localStorage.getItem('uid');
			this.characterName = this.$route.query.characterName;
			this.cid = this.$route.query.cid;
			this.bPublic = this.$route.query.bPublic

			trackWebfunnyEvent(196); // 进入聊天界面

			// 获取本地存储的聊天记录
			const storedChats = localStorage.getItem(`${this.uid}-${this.cid}-chats`);
			if (storedChats) {
				this.chats = JSON.parse(storedChats);
			}
			this.getPicture();

			// 创建 WebSocket 连接
			this.websocket = new WebSocket('wss://service-m974pxd1-1253315760.cd.tencentapigw.com/websocket');

			// 监听 WebSocket 连接开启事件
			this.websocket.onopen = () => {
				console.log('WebSocket connection established.');
				this.startHeartbeat(); // 启动心跳
				this.isConnected = true;
			};
			// 监听 WebSocket 连接关闭事件
			this.websocket.onclose = () => {
				console.log('WebSocket connection closed.');
				this.isConnected = false;

				// 停止心跳
				if (this.heartbeatStopper) {
					this.heartbeatStopper();
				}
			};
			// 监听 WebSocket 收到消息事件
			this.websocket.onmessage = (e) => {
				const message = JSON.parse(e.data);
				const msgType = message.msg_type;

				if (msgType === 're_chat') {
					// 处理聊天
					this.handleChatMessage(message);
				} else if (msgType === 'video_url') {
					// 处理视频
					this.handleVideoMessage(message);
				} else {
					console.log('Unknown message', msgType);
				}
			};
		},

		beforeDestroy() {
			trackWebfunnyEvent(197); // 离开聊天界面

			if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
				this.websocket.close();
			}
			// 停止心跳
			if (this.heartbeatStopper) {
				this.heartbeatStopper();
			}
		},

		methods: {
			getPicture() {
				this.uid = localStorage.getItem('uid');
				this.cid = this.$route.query.cid;
				this.bPublic = this.$route.query.bPublic;

				getPic(this.uid, this.cid, this.bPublic)
					.then(response => {
						const pictureUrl = response.data.picture_url;
						const backUrl = response.data.back_url;

						this.videoUrl = '';
						this.pictureSrc = '';
						this.backUrl = backUrl || '';

						if (pictureUrl && pictureUrl.includes('.mp4')) {
							this.videoUrl = pictureUrl;
							this.isVideoMessage = false;
						} else {
							this.pictureSrc = pictureUrl;
						}
					})
					.catch(error => {
						console.error('Error: ' + error);
					});
			},

			// 启动心跳
			startHeartbeat() {
				this.heartbeatStopper = startHeartbeat(this.websocket, this.uid);
			},

			async sendMessage() {
				if (this.isConnected && this.newMessage.trim() !== '') {
					const record = {
						speaker: 'user',
						msg: this.newMessage.trim()
					};

					// 发送消息到WebSocket服务器
					this.websocket.send(JSON.stringify({
						uid: this.uid,
						cid: this.cid,
						text: record.msg,
						history: this.chats,
						msg_type: 'chat'
					}));
					await this.chats.push(record);
					this.scrollToBottom(); // DOM 更新完成后滚动到底部
					this.saveChatToLocalStorage();
					this.newMessage = ''; // 清空输入框

				} else {
					console.log('WebSocket connection is not established.'); // 连接未建立时输出错误信息
				}
			},

			async handleChatMessage(message) {
				if (message.cid === this.cid) {
					const record = {
						speaker: 'server',
						msg: message.retext
					};
					await this.chats.push(record);
					this.scrollToBottom(); // 每次更新对话滚动到底部
					console.log('Updated chats:', this.chats);
					this.saveChatToLocalStorage();
				}
			},

			scrollToBottom() {
				// 滚动到聊天界面底部
				const chatHistory = this.$refs.chatHistory;
				if (chatHistory) {
					chatHistory.scrollTop = chatHistory.scrollHeight; //滚动条的位置设置为内容的总高度
				}
			},


			handleVideoMessage(message) {
				if (message.cid === this.cid) {
					// 处理视频
					this.videoUrl = message.retext;
					this.isVideoMessage = true;
				}
			},

			saveChatToLocalStorage() {
				localStorage.setItem(`${this.uid}-${this.cid}-chats`, JSON.stringify(this.chats));
			},

			clearChatHistory() {
				// 清空聊天记录
				this.showDialog = true;
			},

			confirm() {
				if (this.chats) {
					this.chats = [];
					this.saveChatToLocalStorage();
				}
				this.showDialog = false;
			},

			cancel() {
				this.showDialog = false;
			},
		}
	}
</script>

<style scoped>
	.main-content {
		flex-direction: column;
		display: flex;
		width: 400px;
		border-radius: 8px;
		padding: 0px 15px 0px 15px;
		box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
	}

	.card {
		margin-top: 10px;
		border-radius: 8px;
		padding: 10px;
		margin-bottom: 10px;
		border: 1px solid #ccc;
	}

	.card h2 {
		margin: 0 10px 10px 10px;
		text-align: center;
	}

	.chat-history {
		max-height: 300px;
		display: flex;
		flex-direction: column;
		overflow-y: auto;
		padding: 0 10px 0 10px;
		border: 1px solid #ccc;
		margin-bottom: 10px;
		border-radius: 8px;
	}

	.chat-input-container {
		display: flex;
		justify-content: center;
		width: 100%;
	}

	.chat-input-textarea {
		overflow-y: auto;
		max-height: 100px;
		flex: 1;
		padding: 10px;
		border: 1px solid #ccc;
		border-radius: 8px;
		font-size: 16px;
		font-family: '微软雅黑';
	}

	.send-button {
		width: 50px;
		padding: 10px;
		background-color: rgb(52, 200, 252);
		color: white;
		border: none;
		cursor: pointer;
		border-radius: 8px;
	}

	.send-button:hover {
		background-color: skyblue;
		border: none;
	}

	.footer {
		text-align: center;
	}

	.clear-button {
		width: 100%;
		max-width: 300px;
		margin: 20px 10px 0 10px;
		background-color: rgb(239, 68, 68);
		color: #fff;
		border: none;
		border-radius: 8px;
		cursor: pointer;
		box-sizing: border-box;
		padding: 8px;
	}

	.clear-button:hover {
		background-color: lightcoral;
		border: none;
	}

	.confirm-box {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		background: white;
		border: 1px solid #ccc;
		padding: 10px;
		box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
		border-radius: 10px;
		max-width: 200px;
		width: 80%;
	}

	.confirm-content p {
		font-size: 15px;
		margin-bottom: 10px;
		margin-top: 10px;
	}

	.confirm-content {
		text-align: center;
	}

	.confirm-content button {
		margin: 10px 25px 0 25px;
		padding: 8px 10px;
		border: none;
		border-radius: 5px;
		cursor: pointer;
		color: black;
		background-color: lightgrey;
	}

	.confirm-content button:hover {
		background-color: grey;
		color: white;
	}
</style>